define(function(require, exports, module) {
  var $ = require("$");
  var bootbox = require("bootbox");
  var dtUtil = require('datatableutil');
  var loader = require("./loader/loader");
  require("bootstrap_commonrequire");
  require("moment");
  require('daterangepicker.css');
  require('bootstrap-daterangepicker');
  require('select2.css');
  require('select2');
//  require('');
  exports.init = function(param) {

    $(document).ready(function() {

      // 加载自定义模板-条件区域
      var template = require("./carrierauditing.tpl");
      var Widget = require("widget");
      var Component = Widget.extend({
        template : template
      });
      new Component({
        renderTo : "seachdiv"
      });
      $("#row1").css({
        "margin-bottom" : "10px"
      });
      $("#applyname").css({
        "margin-left" : "25px"
      });
      $("#applyname").css({
        "margin-left" : "25px"
      });

      // 绑定企业名称下拉列表
      $("#carrierid").select2({
        placeholder : "企业名称",
        allowClear : true,
        ajax : {
          url : GLOBAL.URL.ADMIN_GETCARRIEROPTIONS,
          dataType : 'json',
          delay : 250,
          data : function(term, pageNo) {
            return {
              q : " c.name like '%" + term + "%' ", // search term
              size : 25,
              start : (pageNo - 1) * 25
            };
          },
          results : function(data, pageNo) {
            var dataObj = eval(data);
            /*
             * if(dataObj.length>0){ //如果没有查询到数据，将会返回空串 var more = (pageNo*15)<dataObj.length;
             * //用来判断是否还有更多数据可以加载 return { results:dataObj,more:more }; }else{
             * return {results:dataObj}; }
             */
            return {
              results : dataObj
            };
          },
          cache : true
        }
      });
      /*
       * $.ajax( { type : "POST", dataType : "json", url
       * :GLOBAL.URL.ADMIN_GETCARRIEROPTIONS, async : false, success :
       * function(data) { $("#carrierid").select2({ placeholder : "企业名称",
       * allowClear: true, data: data }); }, error : function(data) {
       * bootbox.alertTimeout('初始化企业名称数据失败！'); } });
       */

      // 绑定isv名称下拉列表
      $.ajax({
        type : "POST",
        dataType : "json",
        url : "/user/queryIsv.do",// GLOBAL.URL.ADMIN_GETCARRIEROPTIONS,//
        // wp.huang
        async : false,
        success : function(data) {
          $("#isvid").select2({
            placeholder : "ISV名称",
            allowClear : true,
            data : data
          });
        },
        error : function(data) {
          bootbox.alertTimeout('初始化ISV名称数据失败！');
        }
      });

      // 绑定APP下拉列表
      $("#applicationid").select2({
        placeholder : "请选择APP",
        allowClear : true,
        ajax : {
          url : "/condition/getAppName.do",
          dataType : 'json',
          delay : 250,
          data : function(term, pageNo) {
            return {
              isvid : $("#isvid").val(),
              q : "a.name like '%"+term+"%'"
            };
          },
          results : function(data, pageNo) {
            var dataObj = eval(data);
            return {
              results : dataObj
            };
          },
          cache : true
        }
      });

      // 审核状态
      var typeList = [ {
        "id" : 0,
        "text" : "未认证"
      }, {
        "id" : 1,
        "text" : "已认证"
      }, {
        "id" : 2,
        "text" : "待审核"
      }, {
        "id" : 3,
        "text" : "审核未通过"
      } ];
      $('#auditingstatus').select2({
        placeholder : "审核状态",
        allowClear : true,
        data : typeList
      });
      // $('#auditingstatus').select2('val',2);

      // 初始化日期范围选择控件
      var DateRange = require('daterangeinput');
      var daterangeAttrs = {
        daterangeId : "querydatewrapper_rang",
        label : "创建时间"
      };
      var daterangeCom = new DateRange({
        attrs : daterangeAttrs,
        renderTo : 'querydatewrapper'
      });

      var Table = require("table");
      new Table({
        attrs : {
          // 设置该table的id
          id : "carrierauditing",
          isHovered : false,
          isStriped : true,
          isBordered : false
        },
        renderTo : param.divWrapperId
      });
      var carrierauditing = $('#carrierauditing').dataTable({
        "sDom" : "<'hidden'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
        "bJQueryUI" : false,
        "oLanguage" : {
          "sUrl" : "/business/js/common/table/src/lang/dataTable.cn.txt"
        },
        "sPaginationType" : "bootstrap", // 分页自带两种样式，full_numbers和two_button(默认)
        "scrollX" : true,
        'bPaginate' : true, // 是否分页
        "bProcessing" : true, // 当datatable获取数据时候是否显示正在处理提示信息。
        "bServerSide" : true, // 指定服务器端分页
        "bDeferRender" : true,
        "bFilter" : true,
        "bInfo" : true,
        "iDisplayLength" : DATATABLES_CONFIG.iDisplayLength.DEFAULT,
        "sAjaxSource" : param.ajaxUrl, // 数据源
        "fnServerData" : function(sSource, aoData, fnCallback, oSettings) {
          var queryparam = dtUtil.convert_aoData(aoData);
          queryparam.q += "";
          var carrierid = $('#carrierid').val();
          var applicationid = $('#applicationid').val();
          var isvid = $('#isvid').val();
          var auditingstatus = $('#auditingstatus').val();
          // 获取时间查询参数
          var daterange = daterangeCom.getPickerRange();

          if (carrierid) {

            if (queryparam.q)
              queryparam.q += ";com.id=" + carrierid;
            else
              queryparam.q += "com.id=" + carrierid;

          }
          if (applicationid) {
            if (queryparam.q)
              queryparam.q += ";app.id=" + applicationid;
            else
              queryparam.q += "app.id=" + applicationid;

          }
          if (isvid) {
            if (queryparam.q)
              queryparam.q += ";isv.id=" + isvid;
            else
              queryparam.q += "isv.id=" + isvid;

          }
          if (auditingstatus) {
            if (queryparam.q)
              queryparam.q += ";com.status=" + auditingstatus;
            else
              queryparam.q += "com.status=" + auditingstatus;
          }
          if (daterange) {
            var daterange = daterange.split("/");
            var startTime = daterange[0];
            var endTime = daterange[1];
            if (queryparam.q)
              queryparam.q += ";com.create_time>='" + startTime + " 00:00:00';com.create_time<='" + endTime + " 23:59:59'";
            else
              queryparam.q += "com.create_time>='" + startTime + " 00:00:00';com.create_time<='" + endTime + " 23:59:59'";
          }
          oSettings.jqXHR = $.ajax({
            "dataType" : 'json',
            "contentType" : "application/json;charset=UTF-8",
            "type" : "GET",
            "url" : sSource,
            "data" : queryparam, // 将请求数据转换为后台要求的JSON格式
            "success" : function(json) {
              if (json.flag == '000000') {
                dtUtil.successCallback(json, aoData, fnCallback);
              } else {
                oauth2Relogin();
              }
            }
          });
        },
        "aaSorting" : [ [ 0, "desc" ] ],
        "aoColumns" : [ {
          "sTitle" : '<input class="only-checkbox" type="checkbox" id="checkall">',
          "bSortable" : false,
          "mData" : "id",
          "mRender" : function(data, type, full) {
            // 将body中的dataArray值赋给dataArray
            var dataArray = $("body").data("dataArray");
            // 判断data是否在dataArray中
            if ($.inArray(data, dataArray) > -1)
              return '<input class="only-checkbox tableCheckbox" type="checkbox" checked>';
            else
              return '<input class="only-checkbox tableCheckbox" type="checkbox">';
          }
        }, {
          "sTitle" : "ISV名称",
          "bSortable" : false,
          "mData" : "isvname"
        }, {
          "sTitle" : "APP名称",
          "bSortable" : false,
          "mData" : "applicationname"
        }, {
          "sTitle" : "企业名称",
          "bSortable" : false,
          "mData" : "carriername"
        }, /*{
          "sTitle" : "账户金额(元)",
          "bSortable" : false,
          "mData" : "amount"
        }, {
          "sTitle" : "赠送金额(元)",
          "bSortable" : false,
          "mData" : "gift"
        },*/
        /*
         * { "sTitle" : "组织机构代码", "bSortable" : false, "mData" :
         * "organizationcode", },
         */
        {
          "sTitle" : "联系人",
          "bSortable" : false,
          "mData" : "contacts"
        }, {
          "sTitle" : "公司电话",
          "bSortable" : false,
          "mData" : "companytel"
        },{
          "sTitle" : "备注",
          "bSortable" : false,
          "mData" : "comments"
        },

        {
          "sTitle" : "审核状态",
          "bSortable" : false,
          "mData" : "auditingstatus",
          "mRender" : function(data, type, full) {
            if (data == 0)
              return "未认证";
            if (data == 1)
              return "已认证";
            if (data == 2)
              return "待审核";
            if (data == 3)
              return "审核未通过";
          }
        }, /*{
                 "sTitle" : "状态",
                 "bSortable" : false,
                 "mData" : "state",
                 "mRender" : function(data, type, full) {
                   if (data == 0)
                     return "停用";
                   if (data == 1)
                     return "启用";
                 }
               }, *//*{
                  "sTitle" : "创建时间",
                  "bSortable" : false,
                  "mData" : "createtime"
                },*/
        /*
         * { "sTitle" : "审核人", "bSortable" : false, "mData" : "auditor", },
         */
        /*{
          "sTitle" : "备注",
          "bSortable" : false,
          "mData" : "remarks"
        }, */{
          "sTitle" : "操作",
          "bSortable" : false,
          "mData" : "auditingstatus",
          "mRender" : function(data, type, full) {
            var ret = '<div class="btn-group" style="margin-top: 8px;">';
//            ret += '<a href="javascript:void(0);" class="btn icon contrast" title="查看图表"></a>';
            ret += '<a href="javascript:void(0);" class="btn icon-reply contrast" title="修改"></a>';
            if (data == 0)
              ret += '<a href="javascript:void(0);" class="btn icon-edit-sign contrast disabled" title="未提交认证信息"></a>';
            if (data == 1)
              ret += '<a href="javascript:void(0);" class="btn icon-edit-sign contrast disabled" title="已认证"></a>';
            if (data == 2)
              ret += '<a href="javascript:void(0);" class="btn icon-edit-sign contrast" title="审核"></a>';
            if (data == 3)
              ret += '<a href="javascript:void(0);" class="btn icon-edit-sign contrast disabled" title="审核未通过"></a>';
            //ret += '<a href="javascript:void(0);" class="btn icon-rocket contrast" title="启用/停用"></a>';
            return ret += '</div>';

          }
        } ],
        "fnDrawCallback" : function(oSettings) {
          var checkboxs = $(".tableCheckbox");
          for ( var i = 0; i < checkboxs.length; i++) {
            var checkbox = checkboxs[i];
            var rowData = carrierauditing.fnGetData(i);
            var auditingstatus = rowData.auditingstatus;
            if (auditingstatus == 0 || auditingstatus == 1 || auditingstatus == 3) {
              $(checkbox).attr("disabled", 'true');
              $(checkbox).removeAttr("checked");
            }
          }

          // 表格绘制完成后，去除width属性，使表格可缩放
          $('#' + oSettings.sTableId).css("width", "");
        }
      });
      // 启用/停用
      $("#carrierauditing tbody").on("click", "tr>td>div>a.icon-rocket", function(e) {
        var rowNode = this.parentNode.parentNode.parentNode;
        var rowData = carrierauditing.fnGetData(rowNode);
        loader.loading("正在提交，请稍等……");
        $.ajax({
          url : "/company/doUpdateState.do",// GLOBAL.URL.ADMIN_INSERTLICENSECARRIER,
          dataType : "json",
          data : "companyid=" + rowData.id,
          type : "POST",
          success : function(json) {
            if (json.flag == '000000') {
              carrierauditing.fnFilter("");
              loader.noloading();
              return false;
            } else {
              oauth2Relogin();
            }
          },
          error : function(s) {
            loader.noloading();
            bootbox.alertTimeout("网络请求失败，请重试！");
          }
        });
      });
      // 批量审批
      $("#creatbtn").on("click", function() {
        var dataArray = $("body").data("dataArray");
        if (!dataArray || dataArray.length <= 0) {
          bootbox.alert("请选择要审批的记录！！！");
          return false;
        }
        auditingaction(dataArray);
      });
      // 审批
      $("#carrierauditing tbody").on("click", "tr>td>div>a.icon-edit-sign", function(e) {
        e = e || window.event;
        var o = e.target || e.srcElement;
        if (o.title != "审核")
          return;
        var rowNode = this.parentNode.parentNode.parentNode;
        var rowData = carrierauditing.fnGetData(rowNode);
        auditingaction(rowData.id);
      });
      
      
      // 修改按钮
      // 设置修改按钮的位置、事件
      $("#carrierauditing tbody").on("click", "tr>td>div>a.icon-reply", function(e) {
        // 将查询条件区隐藏
        $('#seachdiv').hide();
        // 将“批量审核”按钮区隐藏
        $("#optForm").hide();
        // 将数据显示区隐藏
        $("#carrierauditinglistDiv").hide();
        // 获取#carrierauditinglistDiv中的节点
        var rowNode = this.parentNode.parentNode.parentNode;
        // 获取该节点的表单数据
        var rowData = carrierauditing.fnGetData(rowNode);
        // 引用下一界面
        var carrierauditingform = require("./carrierauditingreturnform");
        // 初始化该界面信息
        carrierauditingform.init("data_table_edit", rowData);
        // 将界面信息显示在data_table_edit中
        $('#data_table_edit').show();
      });
      
      // 全选全消
      $("#carrierauditing thead").on("click", "#checkall", function(e) {
        var check = $(this).attr("checked");
        var checkboxs = $(".tableCheckbox");
        var dataArray = $("body").data("dataArray");
        if (!dataArray)
          dataArray = new Array();
        for ( var i = 0; i < checkboxs.length; i++) {
          var checkbox = checkboxs[i];
          var rowData = carrierauditing.fnGetData(i);
          var auditingstatus = rowData.auditingstatus;
          // 如果全选
          if (check == "checked") {
            if (auditingstatus == 2) {
              $(checkbox).attr("checked", 'true');
              dataArray.push(rowData.id);
            } else {
              $(checkbox).attr("disabled", 'true');
              $(checkbox).removeAttr("checked");
            }
          } else {
            if (auditingstatus == 2) {
              $(checkbox).removeAttr("checked");
              dataArray.splice($.inArray(rowData.id, dataArray), 1);
            }
          }
        }
        $("body").data("dataArray", dataArray);
      });
      // 复选框
      $("#carrierauditing tbody").on("click", " tr td .tableCheckbox", function() {
        var rowNode = this.parentNode.parentNode;
        var rowData = carrierauditing.fnGetData(rowNode);
        var check = $(this).attr("checked");
        var dataArray = $("body").data("dataArray");
        if (!dataArray)
          dataArray = new Array();
        if (check)
          dataArray.push(rowData.id);
        else
          dataArray.splice($.inArray(rowData.id, dataArray), 1);

        $("body").data("dataArray", dataArray);
      });
      // 查询
      $('#btnquery').on('click', function() {
        var dataArray = $("body").data("dataArray");
        if (dataArray)
          $("body").data("dataArray", null);
        carrierauditing.fnFilter();
        return false;
      });
      // 重置
      $('#restbtn').on('click', function() {

        $('#carrierid').select2("val", "");
        $('#isvid').select2("val", "");
        $('#applicationid').select2("val", "");
        $('#auditingstatus').select2('val', "");
        daterangeCom.clearInput();

        carrierauditing.fnFilter("");

        return false;
      });
    });
  };

  // 审核弹出窗口
  var auditingaction = function(ids) {
    var auditing = require("./auditing");
    if ($("#auditingid").length <= 0)
      $("body").append("<div id='auditingid'></div>");
    auditing.init({
      "title" : "企业认证审核",
      "renderTo" : "auditingid",
      "passaction" : function(text) {
        var auditMsg = $("#auditing_text").val();
        var data = "id=" + ids + "&auditMsg=" + auditMsg;
        $.ajax({
          url : "/company/doAudit.do",// GLOBAL.URL.ADMIN_LICENSEAUDITING +
          // "0.do",
          dataType : "json",
          type : "POST",
          data : "status=1&" + data,
          success : function(resdata) {
            if (resdata.flag == '000000') {
              $("body").data("dataArray", null);
              $("#carrierauditing").dataTable().fnFilter();
            } else {
              oauth2Relogin();
            }
          }
        });
      },
      "backaction" : function(text) {
        var auditMsg = $("#auditing_text").val();
        var data = "id=" + ids + "&auditMsg=" + auditMsg;
        $.ajax({
          url : "/company/doAudit.do",// GLOBAL.URL.ADMIN_LICENSEAUDITING +
          // "4.do",
          dataType : "json",
          type : "POST",
          data : "status=3&" + data,
          success : function(resdata) {
            if (resdata.flag == '000000') {
              $("body").data("dataArray", null);
              $("#carrierauditing").dataTable().fnFilter();
            } else {
              oauth2Relogin();
            }
          }
        });
      }
    });
  };
});
